<?php
namespace app\api\controller;
use app\admin\model\Chapter;
use app\admin\model\ChapterDetail;
use app\admin\model\Single;
use app\admin\model\TyMember;
use app\admin\model\Voucher;
use app\admin\model\VoucherMember;
use app\api\model\CourseMenu;
use app\api\model\MemberCourseNote;
use think\App;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;


class Question extends Common
{
    private $noCheckAction = [];//不需要验证的方法
    
    public function initialize(){
        parent::initialize();
    }

    /**
     * 获取我的题库
     */
    public function get_my_question_bank(){
        $member       = $this->member;
        $mid          = $member['id'];
        $TyMember     = new TyMember();
        $condition['u.uid'] = $mid;
        $question_bank_info = $TyMember->_get_question_bank($condition,10,'u.id desc');
        $all_number         = $TyMember->_get_all_number($mid);
        $accuracy           = $TyMember->_get_accuracy($mid);
        $right_number       = $TyMember->_get_right_number($mid);
        $back_info['accuracy']     = $accuracy;
        $back_info['right_number'] = $right_number;
        $back_info['all_number']   = $all_number;
        $back_info['question_bank_info'] = $question_bank_info;
        die(apiSuccess($back_info));
    }

    /**
     * 获取我的题库
     */
    public function get_my_question_bank_detail(){
        $request  = $this->request->post();
        $id       = $request['id'];
        $TyMember = new TyMember();
        $condition['u.id'] = $id;
        $question_bank_info = $TyMember->_get_question_detail($condition);
        die(apiSuccess($question_bank_info));
    }

    /**
     * 获取题库章节列表
     */
    public function get_chapter_list(){
        $member   = $this->member;
        $mid      = $member['id'];
        $request  = $this->request->post();
        $cate     = $request['cate'];
        $Model    = new Chapter();
        $question_bank_info = $Model->_get_chapter_list($cate,$mid);
        die(apiSuccess($question_bank_info));
    }

    /**
     * 获取题库章节列表
     */
    public function get_exam_list(){
        $member       = $this->member;
        $mid          = $member['id'];
        $request      = $this->request->post();
        $cate         = $request['cate'];
        $chapter_type = $request['chapter_type'];
        $Model        = new ChapterDetail();
        $question_bank_info = $Model->_get_exam_list($cate,$chapter_type,$mid);
        die(apiSuccess($question_bank_info));
    }

    /**
     * 获取试题
     */
    public function get_test_questions(){
        $member    = $this->member;
        $mid       = $member['id'];
        $request   = $this->request->post();
        $detail_id = $request['detail_id'];
        $Model     = new ChapterDetail();
        $question_bank_info = $Model->_get_test_question($detail_id,$mid);
        die(apiSuccess($question_bank_info));
    }

    /**
     * 收藏试题
     */
    public function collection_question(){
        $request   = $this->request->post();
        $member    = $this->member;
        $mid       = $member['id'];
        $map0['uid']       = $mid;
        $map0['single_id'] = $request['single_id'];
        $is_collection = Db::name('tk_collection')->where($map0)->find();
        if($is_collection){
            die(apiError('已经收藏过了'));
        }
        $insert['uid']       = $mid;
        $insert['single_id'] = $request['single_id'];
        $insert['create_at'] = time();
        $result = Db::name('tk_collection')->insert($insert);
        if($result){
            die(apiSuccess('','收藏成功'));
        }else{
            die(apiError('收藏失败'));
        }
    }

    /**
     * 取消收藏
     */
    public function cancel_collection(){
        $request   = $this->request->post();
        $member    = $this->member;
        $mid       = $member['id'];
        $map0['uid']       = $mid;
        $map0['single_id'] = $request['single_id'];
        Db::name('tk_collection')->where($map0)->delete();
        die(apiSuccess('','取消成功'));
    }

    /**
     * 提交试题
     */
    public function commit_question(){
        //json 字符串
//        [{"single_id":1,"answer":"A","is_right":0,"score":1},{"single_id":2,"answer":"A","is_right":0,"score":1}]
        $request   = $this->request->post();
        $member    = $this->member;
        $mid       = $member['id'];
        try {
            $content = json_decode($request['content'], true);
            if(!is_array($content)){
                die(apiError('格式有误'));
            }
            $total_number = count($content);
            $right_number = 0;
            $wrong_number = 0;
            $total_score  = 0;
            $Record = new Single();
            foreach ($content as $kk=>$vv){
                //is_right 0未做 1做错2 作对
                if($vv['is_right']==1) {  //做错之后假如错题集
                    $Record->_add_wrong($mid,$vv,$request);
                    $wrong_number++;
                }elseif($vv['is_right']==2){
                    $right_number++;
                    $total_score = $total_score+$vv['score'];
                }
            }
        }catch (\Exception $e){
            die(apiError('格式有误'));
        }
        $back_data['total_number'] = $total_number;
        $back_data['right_number'] = $right_number;
        $back_data['wrong_number'] = $wrong_number;
        $back_data['total_score']  = $total_score;
        $record_id = $Record->_add_record($mid,$request,$back_data);

        $back_data['max_score']    = $Record->_max_score($request['detail_id']);
        $back_data['rank_number']  = $Record->_rank_number($total_score,$request['detail_id']);
        $back_data['record_id']    = $record_id;
        $back_data['content']      = $content;
        if($record_id){
            die(apiSuccess($back_data,'提交成功'));
        }else{
            die(apiError('提交失败'));
        }
    }

    /**
     * 查看全部解析
     */
    public function get_all_analysis(){
        $request   = $this->request->post();
        $record_id = $request['record_id'];
        $record_info = Db::name('tk_record')->where('id',$record_id)->find();
        $content     = $record_info['content'];
        $content_arr = json_decode($content,true);
        $question_info = Single::where('detail_id',$record_info['detail_id'])
            ->order('id desc')
            ->all()
            ->toArray();
        $Single = new Single();
        foreach ($question_info as $k=>$v){
            $my_anwser = $Single->get_my_answer($content_arr,$v['id']);
            $question_info[$k]['my_answer'] = $my_anwser;
        }
        die(apiSuccess($question_info));
    }

    /**
     * 查看错题解析
     */
    public function get_wrong_analysis(){
        $request   = $this->request->post();
        $record_id = $request['record_id'];
        $record_info = Db::name('tk_record')->where('id',$record_id)->find();
        $content     = $record_info['content'];
        $content_arr = json_decode($content,true);
        $member    = $this->member;
        $mid       = $member['id'];
        $detail_id   =  $record_info['detail_id'];
        $maps00['uid']       = $mid;
        $maps00['detail_id'] = $detail_id;
        $wrong_arr   =  Db::name('tk_wrong')->where($maps00)->column('single_id');
        if($wrong_arr){
            $question_info = Single::where('detail_id',$record_info['detail_id'])
                ->where('id','in',$wrong_arr)
                ->order('id desc')
                ->all()
                ->toArray();
            $Single = new Single();
            foreach ($question_info as $k=>$v){
                $my_anwser = $Single->get_my_answer($content_arr,$v['id']);
                $question_info[$k]['my_answer'] = $my_anwser;
            }
            die(apiSuccess($question_info));
        }else{
            die(apiError('暂无错题'));
        }

    }

    /**
     * 获取我的收藏
     */
    public function get_my_collection(){
        $member    = $this->member;
        $mid       = $member['id'];
        $maps0['uid']  = $mid;
        $single_id_arr = Db::name('tk_collection')->column('single_id');
        if($single_id_arr){
            $question_info = Single::where('id','in',$single_id_arr)
                ->order('id desc')
                ->all()
                ->toArray();
            die(apiSuccess($question_info));
        }else{
            die(apiError('暂无收藏'));
        }
    }

    /**
     * 获取错题记录数量
     */
    public function get_wrong_numbers(){
        $member    = $this->member;
        $mid       = $member['id'];
        $maps0['uid']  = $mid;
        $Sing = new Single();
        $zjtk = $Sing->_get_wrong_number($mid,1);
        $mnst = $Sing->_get_wrong_number($mid,2);
        $lnzt = $Sing->_get_wrong_number($mid,3);
        $back['zjtk_number'] = $zjtk;
        $back['mnst_number'] = $mnst;
        $back['lnzt_number'] = $lnzt;
        die(apiSuccess($back));
    }

    /**
     * 获取错题记录列表
     */
    public function get_wrong_detail(){
        $request   = $this->request->post();
        $member    = $this->member;
        $mid       = $member['id'];
        $maps0['uid']           = $mid;
        $maps0['chapter_type']  = $request['chapter_type'];
        $wrong_arr = Db::name('tk_wrong')->where($maps0)->select();
        if(!$wrong_arr){
            die(apiError('暂无错题记录'));
        }
       foreach ($wrong_arr as $kk=>$vv){
           $single_info = Db::name('tk_single')->where('id',$vv['single_id'])->find();
           $detail_info = Db::name('tk_chapter_detail')->where('id',$vv['detail_id'])->find();
           $wrong_arr[$kk]['create_at'] = date("Y-m-d H:i:s");
           $wrong_arr[$kk]['q_type']  = $single_info['q_type'];
           $wrong_arr[$kk]['q_title'] = $single_info['q_title'];
           $wrong_arr[$kk]['detail_title'] = $detail_info['detail_title'];
       }
        die(apiSuccess($wrong_arr));
    }

    /**
     * 获取错题记录数据
     */
    public function get_wrong_data(){
        $member    = $this->member;
        $mid       = $member['id'];
        $request   = $this->request->post();
        $chapter_type = $request['chapter_type'];
        $single_id    = $request['single_id'];

        $maps00['u.uid']       = $mid;
        $maps00['u.chapter_type'] = $chapter_type;
        $wrong_arr   =  Db::name('tk_wrong')
            ->alias('u')
            ->field('u.id,u.wrong_answer,s.*')
            ->leftJoin('sy_tk_single s','s.id=u.single_id')
            ->where($maps00)
            ->select();
        if($wrong_arr){
            foreach ($wrong_arr as $kk=>$vv){
                $wrong_arr[$kk]['come_single_id'] = $single_id;
            }
            die(apiSuccess($wrong_arr));
        }else{
            die(apiError('暂无错题'));
        }
    }

    /**
     * 移除错题
     */
    public function remove_wrong(){
        $member    = $this->member;
        $mid       = $member['id'];
        $request   = $this->request->post();
        $single_id           = $request['single_id'];
        $maps00['uid']       = $mid;
        $maps00['single_id'] = $single_id;
        $result       = Db::name('tk_wrong')->where($maps00)->delete();
        if($result){
            die(apiSuccess('','移除成功'));
        }else{
            die(apiError('移除失败'));
        }
    }

    /**
     * 纠错
     */
    public function correction_question(){
        $member    = $this->member;
        $mid       = $member['id'];
        $request   = $this->request->post();
        $maps['uid']        = $mid;
        $maps['single_id']  = $request['single_id'];
        $is_have = Db::name('tk_correction')->where($maps)->find();
        if($is_have){
            die(apiError('已经提交过了'));
        }
        $insert['uid']        = $mid;
        $insert['single_id']  = $request['single_id'];
        $insert['title']      = $request['title'];
        $insert['content']    = $request['content'];
        $insert['create_at']  = time();
        $result       = Db::name('tk_correction')->insert($insert);
        if($result){
            die(apiSuccess('','添加成功'));
        }else{
            die(apiError('添加失败'));
        }
    }

    /**
     * 做题章节/试题记录
     */
    public function done_chapter_record(){
        $request   = $this->request->post();
        $type      = $request['type'];
        $member    = $this->member;
        $mid       = $member['id'];
        if($type==1){
            $maps0[] = ['chapter_type','eq',1];
        }else{
            $maps0[] = ['chapter_type','in',[2,3]];
        }
            $maps0[] = ['uid','eq',$mid];
        $single_info = Db::name('tk_record')
            ->field('detail_id,create_at,content,total_number,right_number,wrong_number,total_score')
            ->where($maps0)
            ->select();
        if(!$single_info){
            die(apiError('暂无试题记录'));
        }
        foreach ($single_info as $k=>$v){
            $detail_title = Db::name('tk_chapter_detail')->where('id',$v['detail_id'])->value('detail_title');
            $done_number  = $v['right_number']+$v['wrong_number'];
            $done_percent = round($done_number/$v['total_number'],4)*100;
            $done_percent = $done_percent.'%';
            $single_info[$k]['detail_title'] = $detail_title;
            $single_info[$k]['done_percent'] = $done_percent;
            $single_info[$k]['create_at']    = date('Y-m-d H:i:s',$v['create_at']);
            unset( $single_info[$k]['content']);
        }
        die(apiSuccess($single_info));
    }

    /**
     * 做题记录查看解析
     */
    public function check_parsing(){
        $request   = $this->request->post();
        $member    = $this->member;
        $mid       = $member['id'];
        $detail_id = $request['detail_id'];
        $maps['uid']       = $mid;
        $maps['detail_id'] = $detail_id;
        $record_info = Db::name('tk_record')->where($maps)->find();
        if(!$record_info){
            die(apiError('暂无数据'));
        }
        $content = $record_info['content'];
        $content = json_decode($content, true);
        $back_data['total_number'] = $record_info['total_number'];
        $back_data['right_number'] = $record_info['right_number'];
        $back_data['wrong_number'] = $record_info['wrong_number'];
        $back_data['total_score']  = $record_info['total_score'];
        $back_data['record_id']    = $record_info['id'];
        $Record = new Single();
        $back_data['max_score']    = $Record->_max_score($request['detail_id']);
        $back_data['rank_number']  = $Record->_rank_number($record_info['total_score'],$request['detail_id']);
        $back_data['content']      = $content;
       die(apiSuccess($back_data));
    }

    /**
     * 删除试题记录
     */
    public function remove_record(){
        $request   = $this->request->post();
        $member    = $this->member;
        $mid       = $member['id'];

        $detail_ids = $request['detail_ids'];
        try{
            $detail_id_arr = json_decode($detail_ids,true);
        }catch (\Exception $e){
            die(apiError('格式有误'));
        }
        $maps[] = ['uid','eq',$mid];
        $maps[] = ['detail_id','in',$detail_id_arr];
        $result = Db::name('tk_record')->where($maps)->delete();
        if($result){
            die(apiSuccess('','删除成功'));
        }else{
            die(apiError('删除失败'));
        }
    }

    /**
     * 做题章节/试题记录
     */
    public function new_chapter_record(){
        $member    = $this->member;
        $mid       = $member['id'];
        $maps0['uid']          = $mid;
        $single_info = Db::name('tk_record')
            ->field('detail_id,create_at,content,total_number,right_number,wrong_number,total_score,chapter_type')
            ->where($maps0)
            ->limit(2)
            ->select();
        if(!$single_info){
            die(apiError('暂无试题记录'));
        }
        foreach ($single_info as $k=>$v){
            $detail_title = Db::name('tk_chapter_detail')->where('id',$v['detail_id'])->value('detail_title');
            $done_number = $v['right_number']+$v['wrong_number'];
            $done_percent = round($done_number/$v['total_number'],4)*100;
            $done_percent = $done_percent.'%';
            $single_info[$k]['detail_title'] = $detail_title;
            $single_info[$k]['done_percent'] = $done_percent;
            $single_info[$k]['create_at']    = date('Y-m-d H:i:s',$v['create_at']);
            unset( $single_info[$k]['content']);
        }
        die(apiSuccess($single_info));
    }

    /**
     * 获取全部分类
     */
    public function get_all_cates(){
        $data = Db::name('course_cate')->select();
        die(apiSuccess($data));
    }

    /**
     * 获取全部分类
     */
    public function get_cate_questions(){
        $request   = $this->request->post();
        $cate_id   = $request['cate_id'];
        $data = Db::name('tk_cates')->where('cate_id',$cate_id)->select();
        foreach ($data as $k=>$v){
            $maps0['cate']         = $v['id'];
            $maps0['chapter_type'] = 1;
            $chapter_number = Db::name('tk_chapter_detail')->where($maps0)->count();

            $maps1['cate']         = $v['id'];
            $maps1['chapter_type'] = ['gt',1];
            $test_number = Db::name('tk_chapter_detail')->where($maps1)->count();
            $data[$k]['chapter_number'] = $chapter_number;
            $data[$k]['test_number']    = $test_number;
        }
        die(apiSuccess($data));
    }

    /**
     * 获取我的题库
     */
    public function get_question_bank_detail(){
        $request  = $this->request->post();
        $id       = $request['id'];
        $TyMember           = new TyMember();
        $condition['id']    = $id;
        $question_bank_info = $TyMember->_get_question_detail_two($condition);
        die(apiSuccess($question_bank_info));
    }



    /**
     * 笔记排序
     */
    public function sort_course_note(){
//        $arr = [
//            ['id'=>16,'sort'=>1],
//            ['id'=>44,'sort'=>2],
//            ['id'=>45,'sort'=>3],
//        ];
//        $arr_string = json_encode($arr);
//        var_dump($arr_string);exit;
        $request = $this->request->post();
        $data    = $request['data'];
        try {
            $data_arr = json_decode($data, true);
        }catch (\Exception $e){
            die(apiError('数据格式有误'));
        }
        $model = new MemberCourseNote();
        foreach ($data_arr as $k=>$v){
            $model->where('id',$v['id'])->update(['sort'=>$v['sort']]);
        }

        die(apiSuccess([], '排序成功'));
    }

    /**
     * 编辑笔记
     */
    public function edit_course_note(){
        $request = $this->request->post();
        if(empty($request['content'])) {
            die(apiError('请输入内容'));
        }
        if(empty($request['id'])) {
            die(apiError('笔记id不能为空'));
        }
        $id = $request['id'];
        $data['content'] = $request['content'];
        $data['created'] = time();
        $model = new MemberCourseNote();
        $ret = $model->_update($data,$id);
        if(!$ret){
            die(apiError($model->getError()));
        }
        die(apiSuccess([], '修改成功'));
    }

    /**
     * 删除笔记
     */
    public function del_course_note(){
        $request = $this->request->post();
        if(empty($request['id'])) {
            die(apiError('笔记id不能为空'));
        }
        $id = $request['id'];
        
        $model = new MemberCourseNote;
        $ret = $model->_delete($id);
        if(!$ret){
            die(apiError($model->getError()));
        }
        die(apiSuccess([], '删除成功'));
    }

    /**
     * 获取可以领取的优惠券
     */
    public function get_vouchers(){
        $request = $this->request->post();
        $status  = $request['status'];
        $member    = $this->member;
        $mid       = $member['id'];
        $status_arr = [1,2,3];
        $time = time();
        if(in_array($status,$status_arr)){
            if(in_array($status,[1,2])){
                $condition[]    = ['u.effective_at','gt',$time];
            }
            $condition[] = ['u.status','eq',$status];
            $condition[] = ['u.mid','eq',$mid];
            $data = VoucherMember::alias('u')
                ->field("u.*,v.name,v.money,v.images,m.user_name")
                ->leftJoin('sy_member m','m.id=u.mid')
                ->leftJoin('sy_voucher v','v.id=u.vid')
                ->order("u.id desc")
                ->where($condition)
                ->select();
        }elseif ($status==4){
            $time = time();
            $condition[]    = ['u.mid','eq',$mid];
            $condition[]    = ['u.effective_at','lt',$time];
            $condition[]    = ['u.status','in',[1,2]];
            $data = VoucherMember::alias('u')
                ->field("u.*,v.name,v.money,v.images,m.user_name")
                ->leftJoin('sy_member m','m.id=u.mid')
                ->leftJoin('sy_voucher v','v.id=u.vid')
                ->where($condition)
                ->order("u.id desc")
                ->select();
        }
        foreach ($data as $k=>$v){
            if($v['effective_at']<time()){
                $data[$k]['is_expired'] = 1;
            }else{
                $data[$k]['is_expired'] = 0;
            }
            $data[$k]['create_at']   = date('Y-m-d H:i:s',$v['create_at']);
            $data[$k]['effective_at'] = date('Y-m-d H:i:s',$v['effective_at']);
        }
        die(apiSuccess($data, '成功'));
    }

    /**
     * 领取优惠券
     */
    public function receive_voucher(){
        $request = $this->request->post();
        $member    = $this->member;
        $id        = $request['id'];
        $mid       = $member['id'];
        $condition['id']     = $id;
        $condition['mid']    = $mid;
        $condition['status'] = 1;
        $voucher_info = Db::name('voucher_member')->where($condition)->find();
        if(!$voucher_info){
            die(apiError('优惠券不存在或已领取过了'));
        }
        if($voucher_info['effective_at']<time()){
            die(apiError('优惠券已过期'));
        }
        Db::name('voucher_member')->where($condition)->update(['status'=>2]);
        die(apiSuccess([], '领取成功'));
    }



    










}
